<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="button">开关</button>
    <script>
        // 初版 不推荐
        // 问题: 所有的状态都在pressButton这一个函数中,后期维护会导致该函数越来越复杂

        /*
        class Swtich {
            constructor(button) {
                this.state = 'off'
                this.button = button

                this.init()
            }

            init() {
                this.button.onclick = () => {
                    this.pressButton()
                }
            }

            pressButton() {
                switch (this.state) {
                    case 'off':
                        this.state = 'on'
                        console.log('灯开了')
                        break;
                    case 'on':
                        this.state = 'off'
                        console.log('灯关了')
                        break;
                    default:
                        break;
                }
            }
        }

        let swtich = new Swtich(document.getElementById('button'))
        */

        // 状态模式 推荐

        class Swtich {
            constructor(button) {
                this.state = new OffState(this)
                this.button = button

                this.offState = new OffState(this)
                this.weakState = new WeakState(this)
                this.strongState = new StrongState(this)

                this.init()
            }

            init() {
                this.button.onclick = () => {
                    this.state.pressButton()
                }
            }

            setState(newState) {
                this.state = newState
            }
        }

        class OffState {
            constructor(swtich) {
                this.swtich = swtich
            }
            pressButton() {
                console.log('弱光')
                this.swtich.setState(this.swtich.weakState)
            }
        }

        class WeakState {
            constructor(swtich) {
                this.swtich = swtich
            }
            pressButton() {
                console.log('强光')
                this.swtich.setState(this.swtich.strongState)
            }
        }

        class StrongState {
            constructor(swtich) {
                this.swtich = swtich
            }
            pressButton() {
                console.log('关灯')
                this.swtich.setState(this.swtich.offState)
            }
        }

        let swtich = new Swtich(document.getElementById('button'))

    </script>
</body>

</html>